package wsdc.app.main;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.security.cert.X509Certificate;

public class TestProxy {
    public static void main(String[] args) {
        OkHttpClient client =createUnsafeClient();

        Request req = new Request.Builder()
                .url("http://uni.wsdchigh.top:5005/vue-fabric-editor?a=b")
                //.header("Host", "uni.wsdchigh.top:31995")
                .build();

        try {
            Response execute = client.newCall(req).execute();
            String string = execute.body().string();
            System.out.println(" result = "+string);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static OkHttpClient createUnsafeClient() {
        try {
            final TrustManager[] trustAllCerts = new TrustManager[] {
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[]{};
                        }
                    }
            };

            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);

            return builder
                    .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.10.21", 31995)))
                    .build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
